import { defineStore } from "pinia";
import { IProduct } from "./product";

export interface IShoppingCart {
  productName: string,
  price: number,
  quantity: number
}

export default defineStore('shoppingCart', {
  state: () => ({
    carts: [] as IShoppingCart[]
  }),
  getters: {
    total(state) {
      let num = 0
      state.carts.forEach(item => {
        num += item.price * item.quantity
      })
      return num
    }
  },
  actions: {
    add(product: IProduct) {
      let entity: IShoppingCart | undefined = this.carts.find(a => a.productName === product.name)
      if (!entity) {
        entity = {
          productName: product.name,
          price: product.price,
          quantity: 1
        } as IShoppingCart
        this.carts.push(entity)
        return
      }
      entity.quantity++
    },
    clear() {
      this.carts = []
    }
  }
})